package com.zmj.controller;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.itextpdf.text.pdf.BaseFont;
import com.zmj.service.impl.GeneratePdfServiceImpl;
import com.zmj.util.PDFUtil;

import io.swagger.annotations.Api;

@RestController
@RequestMapping("/generatepdf/")
@Api("生成pdf文件")
public class GeneratePdfController {

    private Logger log = LoggerFactory.getLogger(GeneratePdfServiceImpl.class);

    /**无用*/
    @RequestMapping(value = "projectExport", method = RequestMethod.GET)
    public void projectExport(HttpServletRequest request, HttpServletResponse response) {
        try {

            Map map=new HashMap<String,Object>();
            map.put("test","测试");
            ByteArrayOutputStream baos = PDFUtil.createPDF("templates/index.html", map);
            //设置response文件头
            PDFUtil.renderPdf(response, baos.toByteArray(), "pdf文件");
            baos.close();
        } catch (Exception e) {
            log.info("导出报错",e);
        }
    }


    @RequestMapping(value = "projectExportCeshi", method = RequestMethod.GET)
    private void createPDF(String fileName , String html)  {
        OutputStream os = null;
        try {
            os = new FileOutputStream(fileName);
            ITextRenderer renderer = new ITextRenderer();

            ITextFontResolver fontResolver = renderer.getFontResolver();
            //指定字体。为了支持中文字体
            fontResolver.addFont("C:/Windows/fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            String content = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"></meta><style type=\"text/css\">     body { font-family: SimSun; }</style>  </head><body>" + html + "</body></html>";
            renderer.setDocumentFromString(content);
            renderer.layout();
            renderer.createPDF(os);
            renderer.finishPDF();
            renderer = null;
        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            try{
                if(os!=null) {
                    os.close();
                }
            }catch (Exception ex1){
                ex1.printStackTrace();
            }
        }
    }
}
